<template>
  <div id="map">{{ lon }}</div>
</template>

<script setup>
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import { onMounted } from "vue";
import { antPath } from "leaflet-ant-path";
import "leaflet-rotatedmarker";
import cars, { begin, end, location, nav } from "@/assets/img.js";
import axios from "axios";
import { useRoute } from "vue-router";
const route = useRoute();

console.log(route.params);
console.log(route.params);

// 转换角度
const calculateBearing = (lat1, lon1, lat2, lon2) => {
  const dLon = (lon2 - lon1) * (Math.PI / 180);
  const y = Math.sin(dLon) * Math.cos(lat2 * (Math.PI / 180));
  const x =
    Math.cos(lat1 * (Math.PI / 180)) * Math.sin(lat2 * (Math.PI / 180)) -
    Math.sin(lat1 * (Math.PI / 180)) *
      Math.cos(lat2 * (Math.PI / 180)) *
      Math.cos(dLon);
  let bearing = Math.atan2(y, x) * (180 / Math.PI);

  // 将方位角规范化为0到360度之间
  if (bearing < 0) {
    bearing = (bearing + 360) % 360;
  }

  return bearing;
};

onMounted(() => {
  const map = L.map("map").setView([route.params.lat, route.params.lon], 12);
  // const map = L.map("map").setView([route.params.lat, route.params.lon], 10);

  L.tileLayer("http://65.29.3.154:89/roadmap/{z}/{x}/{y}.png", {
    minZoom: 7,
    maxZoom: 16,
    attribution: "",
  }).addTo(map);

  let layerGroups = L.layerGroup().addTo(map);

  const marker = L.marker([route.params.lat, route.params.lon], {
      icon: L.icon({
        iconUrl: nav, // 图标图片的URL
        iconSize: [32, 32], // 图标的大小
        iconAnchor: [15, 15], // 图标的锚点，即图标的位置应该放置在地图上的位置
        popupAnchor: [-3, -76], // 弹出框的锚点，即当你点击图标时，弹出框应该出现在哪个位置
      }),
    })
      .addTo(layerGroups)
      .bindTooltip(
        `${route.params.vehicleNo}， 开始时间：${route.params.mintime}`,
        { permanent: true, direction: "top", offset: [0, -20] }
      )
      .openTooltip();

  

  // 绘线
  function drawPolyline(points) {
    if (points.length === 0) {
      return;
    }

    if (layerGroups) {
      map.removeLayer(layerGroups);
      layerGroups = L.layerGroup().addTo(map);
    } else {
      layerGroups = L.layerGroup().addTo(map);
    }

    // 起始点
    const marker = L.marker(points[0], {
      icon: L.icon({
        iconUrl: nav, // 图标图片的URL
        iconSize: [32, 32], // 图标的大小
        iconAnchor: [15, 15], // 图标的锚点，即图标的位置应该放置在地图上的位置
        popupAnchor: [-3, -76], // 弹出框的锚点，即当你点击图标时，弹出框应该出现在哪个位置
      }),
    })
      .addTo(layerGroups)
      .bindTooltip(
        `${route.params.vehicleNo}， 开始时间：${route.params.mintime}`,
        { permanent: true, direction: "top", offset: [0, -20] }
      )
      .openTooltip();

    // 线
    L.polyline
      .antPath(points, {
        // 点的集合
        color: "#006600",
        fillColor: "#006600",
        pulseColor: "#e5ffe5",
        opacity: 6,
        delay: 10000,
        dashArray: [5, 30],
      })
      .addTo(layerGroups);

    // 最新的点
    L.marker(points[points.length - 1], {
      icon: L.icon({
        iconUrl: location,
        iconSize: [30, 30], // icon的大小
        iconAnchor: [16, 15], // icon的渲染的位置（相对与marker）
        shadowAnchor: [0, 0], // shadow的渲染的位置（相对于marker）
        popupAnchor: [0, 0], //若是绑定了popup的popup的打开位置（相对于icon）
      }),
      title: "终点",
      draggable: true,
      rotationAngle:
        points.length > 1
          ? calculateBearing(
              points[points.length - 2][0],
              points[points.length - 2][1],
              points[points.length - 1][0],
              points[points.length - 1][1]
            )
          : 0,
    })
      .addTo(layerGroups)
      .bindTooltip(
        `${route.params.vehicleNo}，结束时间：${route.params.maxtime}`,
        { permanent: true, direction: "top", offset: [0, -20] }
      )
      .openTooltip();
  }

  function draw() {
    const formData = new FormData();
    formData.append("vehicleNo", route.params.vehicleNo);
    axios
      .post(
        "http://65.29.3.198:60089/YzFatigueDriving/YzPljs/list/vehiceleLonlatList",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      )
      .then((res) => {
        let points = [];
        const arr = JSON.parse(res.data[0]["middlelonlat"]);
        for (let i = 0; i < arr.length; i++) {
          const pointArr = arr[i].split(",");
          points.push([Number(pointArr[1]), Number(pointArr[0])]);
        }
        drawPolyline(points);
      })
      .catch((error) => {
        console.log("实时轨迹");
        console.log(error);
      });
  }
  
  draw();
  setInterval(() => {
    draw();
  }, 30*1000)
});
</script>

<style scoped>
#map {
  height: 100%;
}
</style>
